<script lang="ts" setup>
import { ref, reactive, onBeforeUnmount } from "vue"
import { formatDateTime } from "@/utils"

import {
  type FormInstance,
  type FormRules,
  ElMessage,
  type TabsPaneContext,
  type UploadUserFile,
  type UploadProps
} from "element-plus"
import { rechargeAdd, testadd, recListApi, callQuery } from "@/api/vouchercenter/index"
import { Search } from "@element-plus/icons-vue"

// #region 用户数据
const activeName = ref("first")
const ruleFormRef = ref<FormInstance>()
const ruleFormRefA = ref<FormInstance>()
const btnDis = ref<boolean>(false)
const ruleForm = reactive<any>({
  cellPhone: "", // 手机号
  operator: "", // 运营商
  denomination: "", // 充值面额
  image: "", // 图片
  orderReference: "", // 订单编号
  rests: "", // 其他自定义备注
  remark: "" // 备注
})
// 充值提示框
const dialogVisible = ref(false)
const radionButton = reactive([
  {
    lable: "移动",
    value: "0"
  },
  {
    lable: "电信",
    value: "1"
  },
  {
    lable: "联通",
    value: "2"
  },
  {
    lable: "河南电信",
    value: "3"
  },
  {
    lable: "广电",
    value: "4"
  }
])
const radionButtonLISt = ref([]) // 运营商面额
//  #endregion

// #region 上传图片
import { getToken } from "@/utils/cache/cookies"
const headersOpts = {
  token: getToken()
}
const fileList = ref<UploadUserFile[]>([])
const dialogImageUrl = ref("")
const dialogVisibleIMG = ref(false)
//  多张图片上传 发布时图片改变
const handleChageImg1 = (file: any, resfileList: any) => {
  const size = ref(2)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
    fileList.value = resfileList.filter((item: any) => item.uid !== file.uid) /**不符合规定的图片不在照片墙展示 */
  } else {
    ruleForm.image = resfileList
      .map((item: any) => {
        return item.response?.data.split("/image/")[1]
          ? item.response?.data.split("/image/")[1]
          : item.url.split("/image/")[1]
      })
      .join(",")
  }
}
// 多张图片 移除图片
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFiles, 180)
  // fileList1.value = uploadFiles
  ruleForm.image = uploadFiles
    .map((item: any) => {
      return item.response?.data.split("/image/")[1]
        ? item.response?.data.split("/image/")[1]
        : item.url.split("/image/")[1]
    })
    .join(",")
}
// 放大查看图片
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisibleIMG.value = true
}
// #endregion

// #region 手机号正则表达式
const checkPhone = (rule: any, value: any, callback: any) => {
  const regMobile = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
  const isChinaMobile = /^1(3[4-9]|4[7]|5[012789]|7[28]|8[23478]|9[578])\d{8}$/ //移动  0
  // const isChinaTelcom = /^1(3[3])|(5[3])|(7[37])|(8[019])|(9[039])\d{8}$/ //电信  1
  const isChinaTelcom = /^((133)|(153)|(17[3|7])|(18[0|1|9])|(19[0139]))[\d]{8}$/ //电信  1
  const isChinaUnion = /^(130|131|132|145|155|156|166|175|176|185|186|196)\d{8}$/ //联通  2
  const isChinaGD = /^1(9[2])\d{8}$/ //广电  4
  if (regMobile.test(value)) {
    console.log(value, "手机号")
    // callback()
    if (isChinaMobile.test(value)) {
      ruleForm.operator = "0"
      // 根据运营商查看充值面额
      callQuery({ shop: ruleForm.operator }).then((res: any) => {
        console.log(res, "000")
        radionButtonLISt.value = res.data
      })
      //
      callback()
    } else if (isChinaTelcom.test(value)) {
      ruleForm.operator = "1"
      callQuery({ shop: ruleForm.operator }).then((res: any) => {
        console.log(res, "111")
        radionButtonLISt.value = res.data
      })
      callback()
    } else if (isChinaUnion.test(value)) {
      ruleForm.operator = "2"
      callQuery({ shop: ruleForm.operator }).then((res: any) => {
        console.log(res, "222")
        radionButtonLISt.value = res.data
      })
      callback()
    } else if (isChinaGD.test(value)) {
      ruleForm.operator = "4"
      callQuery({ shop: ruleForm.operator }).then((res: any) => {
        console.log(res, "444")
        radionButtonLISt.value = res.data
      })
      callback()
    }
  }
  console.log(value, "11")
  callback(new Error("请输入合法的手机号"))
}
const rules = reactive<FormRules>({
  cellPhone: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    { type: "number", validator: checkPhone }
  ],

  operator: [
    {
      required: true,
      message: "请选择一个所属运营商",
      trigger: "change"
    }
  ],
  denomination: [{ required: true, message: "请选择一个充值面额", trigger: "change" }],
  remark: [{ required: true, message: "请选择备注", trigger: "change" }],
  orderReference: [{ required: true, message: "请输入订单编号", trigger: "blur" }]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      dialogVisible.value = true
      btnDis.value = true
      console.log(ruleForm.image, "验证成功!")
      // ruleForm.resetFields()
      rechargeAdd({
        cellPhone: ruleForm.cellPhone,
        denomination: ruleForm.denomination,
        image: ruleForm.image,
        remark: ruleForm.remark,
        orderReference: ruleForm.orderReference,
        rests: ruleForm.rests,
        shop: ruleForm.operator
      })
        .then((res) => {
          console.log(res)
          // 17621375308
          btnDis.value = false
          ElMessage.success("充值成功")
          ruleFormRef.value?.resetFields()
          ruleForm.image = ""
          fileList.value = []
        })
        .finally(() => {
          btnDis.value = false
        })
    } else {
      console.log("验证失败!", fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  btnDis.value = false
}
// #endregion

// #region 批量充值
const ruleFormA = reactive({
  cellPhone: "", // 手机号
  operator: "", // 运营商
  denomination: "", // 充值面额
  rests: "", // 其他自定义备注
  remark: "" // 备注
})
const cellPhoneList = ref() // 批量充值手机号数组
const cellPhoneCG = ref() // 成功手机号
const cellPhoneCGList = ref<any>([]) //  批量充值成功手机号数组
const cellPhoneSB = ref() // 失败手机号
const cellPhoneSBList = ref<any>([]) // 批量充值失败手机号数组
let sum = 0
const loading = ref(false) //页面
const loadingA = ref(false) //按钮
const loadingB = ref(false) //循环

const timerTimeout = ref() //定时器名字

const submitFormA = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (ruleFormA.cellPhone !== "") {
        // console.log(ruleFormA, "验证成功!")
        loading.value = true
        loadingA.value = true
        loadingB.value = true
        cellPhoneList.value = ruleFormA.cellPhone
        console.log(cellPhoneList.value, "获取号码")
        sum = cellPhoneList.value.length
        const i = ref(0)
        timerTimeout.value = setInterval(() => {
          if (loadingB.value == true) {
            loadingB.value = false
            if (i.value == sum) {
              ElMessage.success("充值成功")
              loading.value = false
              return
            }
            testadd({
              cellPhone: cellPhoneList.value[i.value],
              denomination: ruleFormA.denomination,
              shop: ruleFormA.operator,
              rests: ruleFormA.rests,
              remark: ruleFormA.remark
            }).then((res: any) => {
              loadingB.value = true
              i.value++
              if (res.data.code == 200) {
                cellPhoneCG.value = res.data.phone
                cellPhoneCGList.value.push(cellPhoneCG.value)
                // console.log(cellPhoneCGList.value, "888")
              }
              if (res.data.code == 400) {
                // console.log(res, "失败")
                cellPhoneSB.value = res.data.phone
                cellPhoneSBList.value.push(cellPhoneSB.value)
                // console.log("失败", cellPhoneSBList.value)
              }
            })
          }
        }, 1)
      } else {
        ElMessage.error('请检查是否填写完整"')
      }
    } else {
      console.log("验证失败!", fields)
      ElMessage.error('请检查是否填写完整"')
    }
  })
}
const TZbutton = () => {
  loading.value = false
  loadingB.value = false
  ElMessage.error("暂停充值")
  clearInterval(timerTimeout.value)
}
const ChangeClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab.props.name, event)

  if (tab.props.name == "first") {
    clearInterval(timerTimeout.value)
    loading.value = false
    loadingB.value = false
  }
}

const resetFormA = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  ruleFormA.cellPhone = ""
  aLength.value = 0
  uploadFiles.value = []
  loadingA.value = false
}
// #endregion

// #region txt文件上传
const uploadFiles = ref([])
const loadJsonFromFile = (file: any, fileList: any) => {
  uploadFiles.value = fileList
  console.log(uploadFiles.value, "123")
}
const file = ref<any>({})
const fileString = ref<any>({})
const aLength = ref(0)
const submit = () => {
  // 解析上传的文件
  file.value = uploadFiles.value[0]
  const reader = new FileReader()
  // abort none 中断读取
  // readAsBinaryString file 将文件读取为二进制码，通常我们将它传送到后端，后端可以通过这段字符串存储文件
  // readAsDataURL file 将文件读取为 DataURL，一段以 data: 开头的字符串，这段字符串的实质就是 Data URL，Data URL是一种将小文件直接嵌入文档的方案。这里的小文件通常是指图像与 html 等格式的文件
  // readAsText file, [encoding] 将文件读取为文本，读取的结果即是这个文本文件中的内容
  reader.readAsText(file.value.raw)
  // onabort 中断时触发
  // onerror 出错时触发
  // onload 文件读取成功完成时触发
  // onloadend 读取完成触发，无论成功或失败
  // onloadstart 读取开始时触发
  // onprogress 读取中
  reader.onload = (e) => {
    // 读取文件内容
    fileString.value = e.target?.result
    // 接下来可对文件内容进行处理
    console.log(fileString.value, "读取文件内容")
    let a = fileString.value.replace(/\s*/g, "").split(",")
    aLength.value = a.length
    // let a = fileString.value.split(",")
    const b = ref<any>([])
    console.log(a, "分割空格")
    const reg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
    if (a.length > 20000) {
      a = ""
      aLength.value = 0
      ElMessage.error("不能超过1万单")
    }
    a.forEach(function (item: any) {
      if (!reg.test(item)) {
        console.log(item)
        b.value.push(item)
        a = ""
      } else {
        ruleFormA.cellPhone = a
      }
    })
    if (b.value.length > 0) {
      ruleFormA.cellPhone = ""
      alert(b.value + "手机号码有误，请重新输入！")
    }
    // ruleFormA.cellPhone = fileString.value.split(",").join()
  }
}
//充值记录查询
const open1 = ref<boolean>(false)
const recList = ref<any>([])
const recList1 = ref<any>([])
const dc = ref("")
const dc2 = ref("")
const orderSearch = (val: any) => {
  recListApi({ phoneNumber: val }).then((res: any) => {
    open1.value = true
    console.log(res)
    dc.value = res.data.directCharge
    dc2.value = res.data.manualPickup
    recList.value = res.data.numberList
    recList1.value = res.data.numberLists
  })
}

onBeforeUnmount(() => {
  clearInterval(timerTimeout.value)
})
// 批量充值获取面额
const getcallQuery = (newValue: any) => {
  console.log(newValue, 11)
  callQuery({ shop: newValue }).then((res: any) => {
    radionButtonLISt.value = res.data
  })
}
</script>

<template>
  <div class="app-container">
    <el-card>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="ChangeClick">
        <el-tab-pane label="手工填写" name="first">
          <!-- 手工填写 -->
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="120px"
            class="demo-ruleForm"
            status-icon
          >
            <el-form-item label="充值号码" prop="cellPhone">
              <el-input
                v-model.number="ruleForm.cellPhone"
                @blur="orderSearch(ruleForm.cellPhone)"
                style="width: 280px"
              />
              <el-button
                type="primary"
                :icon="Search"
                style="margin-left: 15px"
                @click="orderSearch(ruleForm.cellPhone)"
                >记录查询</el-button
              >
            </el-form-item>
            <el-form-item label="所属运营商" prop="operator">
              <el-radio-group v-model="ruleForm.operator" class="button" @change="getcallQuery">
                <!-- <el-radio-button
                  :disabled="ruleForm.operator !== item.value && ruleForm.operator !== ''"
                  v-for="item in radionButton"
                  :key="item.lable"
                  :label="item.value"
                  >{{ item.lable }}</el-radio-button
                > -->
                <el-radio-button :disabled="ruleForm.operator !== '0'" label="0">移动</el-radio-button>
                <el-radio-button :disabled="ruleForm.operator !== '1' && ruleForm.operator !== '3'" label="1"
                  >电信</el-radio-button
                >
                <el-radio-button :disabled="ruleForm.operator !== '2'" label="2">联通</el-radio-button>
                <el-radio-button :disabled="ruleForm.operator !== '1' && ruleForm.operator !== '3'" label="3"
                  >河南电信</el-radio-button
                >
                <el-radio-button :disabled="ruleForm.operator !== '4'" label="4">广电</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="充值面额" prop="denomination">
              <el-radio-group v-model="ruleForm.denomination">
                <el-radio-button v-for="(item, index) in radionButtonLISt" :key="index" :label="item" />
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="remark" label="充值内容">
              <el-select v-model="ruleForm.remark" placeholder="请选择备注信息" clearable>
                <el-option label="话费补贴" value="话费补贴" />
                <el-option label="补偿充值" value="补偿充值" />
                <el-option label="激活奖励" value="激活奖励" />
                <el-option label="投诉补偿" value="投诉补偿" />
                <el-option label="卡费补贴" value="卡费补贴" />
                <el-option label="评价补贴" value="评价补贴" />
                <el-option label="返首冲" value="返首冲" />
                <el-option label="返首月月租" value="返首月月租" />
                <el-option label="公司返费" value="公司返费" />
                <el-option label="其他" value="其他" />
              </el-select>
              <el-input
                v-if="ruleForm.remark == '其他'"
                v-model="ruleForm.rests"
                placeholder="自定义内容"
                style="width: 280px"
              />
            </el-form-item>
            <el-form-item label="订单编号" prop="orderReference">
              <el-input v-model="ruleForm.orderReference" maxlength="25" show-word-limit style="width: 280px" />
            </el-form-item>
            <el-form-item prop="image" label="上传图片">
              <el-upload
                :multiple="false"
                :limit="1"
                v-model:file-list="fileList"
                action="api/order/package/upload"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-change="handleChageImg1"
                :headers="headersOpts"
                accept="image/*"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
              <el-dialog v-model="dialogVisibleIMG">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
              </el-dialog>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)" :disabled="btnDis"> 确定 </el-button>
              <el-button @click="resetForm(ruleFormRef)">清空</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane
          label="批量充值"
          name="two"
          v-loading="loading"
          :element-loading-text="`充值中请勿刷新页面,成功手机号:${cellPhoneCGList.length}`"
        >
          <el-form
            ref="ruleFormRefA"
            :model="ruleFormA"
            :rules="rules"
            label-width="120px"
            class="demo-ruleForm"
            status-icon
          >
            <div style="margin-bottom: 10px">
              <div style="display: flex">
                <el-upload
                  ref="upload"
                  accept=".txt"
                  action="alert"
                  :auto-upload="false"
                  :file-list="uploadFiles"
                  :on-change="loadJsonFromFile"
                  :limit="1"
                >
                  <el-button type="success">选取文件</el-button>
                </el-upload>
                <el-button style="margin-left: 10px" type="primary" @click="submit">上传</el-button>
              </div>

              <el-text class="mx-1" type="danger"
                >注意事项：
                <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1.先选取文件在点击上传,文件上传格式为.txt,
                内容格式为1xxxxxxxxxx,1xxxxxxxxx...,手机号与手机号之间用英文逗号隔开并且结尾没有任何符号
                <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2.充值成功后核对完成后再刷新页面
                <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;3.充值号码运营商相同充值金额相同
                <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;4.点击清空之后才能再次充值
                <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;5.单次充值只能充值1万单
              </el-text>
            </div>
            <div class="PLBOx">
              <div>
                <!-- <el-text class="mx-1" type="primary">{{ aLength }}</el-text> -->
                <span>充值号码数量: {{ aLength }}</span>
                <el-form-item>
                  <el-input
                    :rows="10"
                    v-model="ruleFormA.cellPhone"
                    type="textarea"
                    resize="none"
                    disabled
                    style="white-space: pre-line; width: 280px"
                    placeholder="如：155xxxxxxxx,155xxxxxxxx"
                  />
                </el-form-item>
              </div>

              <div class="CGbox">
                <span>成功手机号: {{ cellPhoneCGList.length }}</span>
                <el-scrollbar height="220px">
                  <el-input
                    :rows="10"
                    v-model="cellPhoneCGList"
                    type="textarea"
                    resize="none"
                    disabled
                    style="white-space: pre-line; width: 280px"
                  />
                </el-scrollbar>
              </div>
              <div class="SBbox">
                <span>失败手机号: {{ cellPhoneSBList.length }}</span>
                <el-scrollbar height="220px">
                  <el-input
                    :rows="10"
                    v-model="cellPhoneSBList"
                    type="textarea"
                    resize="none"
                    disabled
                    style="white-space: pre-line; width: 280px"
                  />
                </el-scrollbar>
              </div>
            </div>
            <el-form-item label="所属运营商" prop="operator">
              <el-radio-group v-model="ruleFormA.operator" class="button" @change="getcallQuery">
                <el-radio-button v-for="item in radionButton" :key="item.lable" :label="item.value">{{
                  item.lable
                }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="充值面额" prop="denomination">
              <el-radio-group v-model="ruleFormA.denomination">
                <el-radio-button v-for="(item, index) in radionButtonLISt" :key="index" :label="item" />
              </el-radio-group>
            </el-form-item>
            <el-form-item prop="remark" label="充值内容">
              <el-select v-model="ruleFormA.remark" placeholder="请选择备注信息" clearable>
                <el-option label="话费补贴" value="话费补贴" />
                <el-option label="补偿充值" value="补偿充值" />
                <el-option label="激活奖励" value="激活奖励" />
                <el-option label="投诉补偿" value="投诉补偿" />
                <el-option label="卡费补贴" value="卡费补贴" />
                <el-option label="评价补贴" value="评价补贴" />
                <el-option label="返首冲" value="返首冲" />
                <el-option label="返首月月租" value="返首月月租" />
                <el-option label="公司返费" value="公司返费" />
                <el-option label="其他" value="其他" />
              </el-select>
              <el-input
                v-if="ruleFormA.remark == '其他'"
                v-model="ruleFormA.rests"
                placeholder="自定义内容"
                style="width: 280px"
              />
            </el-form-item>
            <el-form-item>
              <el-button :disabled="loadingA == true" type="primary" @click="submitFormA(ruleFormRefA)">
                确定
              </el-button>
              <el-button @click="resetFormA(ruleFormRefA)">清空</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-button class="ztbutton" size="large" v-if="loading && activeName == 'two'" type="danger" @click="TZbutton"
          >停止</el-button
        >
      </el-tabs>
    </el-card>
    <!-- 充值/领取记录 -->
    <el-dialog title="返费记录" v-model="open1" width="100%" append-to-body>
      <el-row :gutter="20">
        <el-col :span="13">
          <h4>追创科技充值记录(金额：{{ dc }})</h4>
          <el-table v-loading="loading" :data="recList">
            <el-table-column label="充值时间" align="center" key="createTime" prop="createTime">
              <template #default="scope">
                <span>{{ formatDateTime(scope.row.date) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="账户名" align="center" key="userName" prop="userName" />
            <el-table-column label="手机号" align="center" key="phone" prop="phone" />
            <el-table-column label="充值金额" align="center" key="amount" prop="amount" />
            <el-table-column label="实扣金额" align="center" key="realityAmount" prop="realityAmount" />
            <el-table-column label="充值状态" align="center" key="state" prop="state" />
            <el-table-column label="佣金状态" align="center" key="commissionState" prop="commissionState" />
          </el-table>
        </el-col>
        <el-col :span="11">
          <h4>追创科技2.0用户领取记录(金额：{{ dc2 }})</h4>
          <el-table v-loading="loading" :data="recList1" width="200">
            <el-table-column label="领取时间" align="center" key="createTime" prop="createTime">
              <template #default="scope">
                <span>{{ formatDateTime(scope.row.date) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="手机号" align="center" key="phone" prop="phone" :show-overflow-tooltip="true" />
            <el-table-column label="领取金额" align="center" key="amount" prop="amount" />
            <el-table-column label="实扣金额" align="center" key="realityAmount" prop="realityAmount" />
            <el-table-column label="领取状态" align="center" key="state" prop="state" />
          </el-table>
        </el-col>
      </el-row>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="open1 = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.PLBOx {
  display: flex;
}
.CGbox {
  width: 280px;
  height: 220px;
  margin-left: 40px;
}
.SBbox {
  width: 280px;
  height: 220px;
  margin-left: 40px;
}
.ztbutton {
  margin-left: 45%;
}
</style>
